<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;



class GoodsController extends HomeController
{
    //店铺列表
	public function shop_list(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
	        $u_lng = $input['u_lng']?$input['u_lng']:0;//经度
	        $u_lat = $input['u_lat']?$input['u_lat']:0;//纬度
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $str=($n-1)*$num+2;
            $top_user = M('user')->field('id,nickname,avatar_img,lng,lat')->limit(0,2)->select();
            foreach($top_user as $k=>$v){
                $top_user[$k]['avatar_img']=get_avatar($v['id']);
                $map['uid'] = $v['id'];
                $goods_num = M('goods')->where($map)->count();
                $top_user[$k]['goods_num']=$goods_num;
                $top_user[$k]['distance'] = getDistance_map($v['lng'],$v['lat'],$u_lng,$u_lat);
                unset($top_user[$k]['lng']);
                unset($top_user[$k]['lat']);
            }

            $users=M('user')->field('id,nickname,avatar_img')->limit($str,$num)->select();
            foreach($users as $k=>$v){
                $users[$k]['avatar_img']=get_avatar($v['id']);
                $map['uid']=$v['id'];
                $goods_num=M('goods')->where($map)->count();
                $users[$k]['goods_num']=$goods_num;
                $users[$k]['distance'] = getDistance_map($v['lng'],$v['lat'],$u_lng,$u_lat);
                unset($users[$k]['lng']);
                unset($users[$k]['lat']);
            }

            $data = [
                    'top' => $top_user?$top_user:[],
                    'user' => $users?$users:[]
            ];

            if($top_user){
                return api_return(1,'success',$data);
            }else{
                return api_return(1,'无数据',array());
            }
        }
	}

	//店铺搜索
	public function shop_list_search(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
	        $u_lng = $input['u_lng']?$input['u_lng']:0;//用户经度
	        $u_lat = $input['u_lat']?$input['u_lat']:0;//用户纬度
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;
            $nickname = $input['nickname'];//店铺名称

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if($nickname) $where['nickname'] = array('like','%'.$nickname.'%');

            $str=($n-1)*$num;

            $users=M('user')->field('id,nickname,avatar_img,lng,lat')->where($where)->limit($str,$num)->select();
            foreach($users as $k=>$v){
                $users[$k]['avatar_img']=get_img($v['avatar_img']);
                $map['uid']=$v['id'];
                $goods_num=M('goods')->where($map)->count();
                $users[$k]['goods_num']=$goods_num;
                $users[$k]['distance'] = getDistance_map($v['lng'],$v['lat'],$u_lng,$u_lat);
                unset($users[$k]['lng']);
                unset($users[$k]['lat']);
            }

            if($users){
                return api_return(1,'success',$users);
            }else{
                return api_return(1,'无数据',array());
            }
        }
	}

	//商品列表
	public function  goods_list(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'uid不能为空');

            $str=($n-1)*$num;

            $where['uid'] = $uid;
            $where['status'] = array('neq',2);
            $res=M('goods')->field('id,name,price,num,desc,imgs,status')->where($where)->limit($str,$num)->select();
            if($res){
                foreach($res as $k=>$v){
                    $img=explode(',',$v['imgs']);
                    $img=getImgurl($img[0]);
                    $res[$k]['image']=$img;
                    unset($res[$k]['imgs']);
                }
                return api_return(1,'success',$res);
            }else{
                return api_return(1,'无数据',array());
            }
        }

	}

	//发布商品
	public function add_goods()
	{
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                $input = I('post.');
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $name = $input['name'];
            $price = $input['price'];
            $num = $input['num'];
            $desc = $input['desc'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'uid不能为空');
            if(empty($name)) return api_return(2,'请输入商品名称');
            if(empty($price)) return api_return(2,'请输入商品价格');
            if(empty($num)) return api_return(2,'请输入商品库存');
            if(empty($desc)) return api_return(2,'请输入商品描述');

            //上传多图
            $base_imgs = $input['base_imgs'];
            $file = $_FILES['imgs'];

            if(empty($base_imgs) && count($file['tmp_name']) == 0) return api_return(2,'请传入商品图片');

            if($base_imgs){
                $img_ids = base64_all_img($base_imgs);
                $imgs = substr($img_ids,0,-1);
            }else{
                if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                    mkdir("Uploads/Picture/" . date("Y-m-d"));
                }

                $imgid = array();
                for ($i = 0; $i < count($file['tmp_name']); $i++) {
                    $str = stristr($file['name'][$i], '.');
                    if ($str != '') {
                        $path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "goods" . $uid . $str;
                    } else {
                        $path = '';
                    }

                    if ($path != '') {
                        if (copy($file['tmp_name'][$i], $path)) {
                            $imgurl['path'] = "/" . $path;
                            $imgurl['status'] = 1;
                            $imgurl['create_time'] = time();
                            $picture_id = D('picture')->add($imgurl);
                            if ($picture_id) {
                                //$picture[$i]['id'] = intval($picture_id);
                                $imgid[] = $picture_id;
                            }
                        } else {
                            return api_return(2,'提交失败');
                        }
                    }
                    sleep(0);
                }
                $imgs = implode(',', $imgid);
            }


            //上传多图（描述图片）
            $base_desc_imgs = $input['base_desc_imgs'];
            $file_desc = $_FILES['desc_imgs'];
            file_put_contents(RUNTIME_PATH.'goods_desc.txt',json_encode($file_desc));

            if(empty($base_desc_imgs) && count($file_desc['tmp_name']) == 0) return api_return(2,'请上传商品描述图片');

            if($base_desc_imgs){
                $desc_img_ids = base64_all_img($base_desc_imgs);
                $imgs_desc = substr($desc_img_ids,0,-1);
            }else{
                if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                    mkdir("Uploads/Picture/" . date("Y-m-d"));
                }

                $imgid_desc = array();
                for ($i = 0; $i < count($file_desc['tmp_name']); $i++) {
                    $str = stristr($file_desc['name'][$i], '.');
                    if ($str != '') {
                        $path_desc = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "desc" . $uid . $str;
                    } else {
                        $path_desc = '';
                    }

                    if ($path_desc != '') {
                        if (copy($file_desc['tmp_name'][$i], $path_desc)) {
                            $imgurl_desc['path'] = "/" . $path_desc;
                            $imgurl_desc['status'] = 1;
                            $imgurl_desc['create_time'] = time();
                            $picture_id_desc = D('picture')->add($imgurl_desc);
                            if ($picture_id_desc) {
                                //$picture[$i]['id'] = intval($picture_id);
                                $imgid_desc[] = $picture_id_desc;
                            }
                        } else {
                            return api_return(2,'提交失败');
                        }
                    }
                    sleep(0);
                }
                $imgs_desc = implode(',', $imgid_desc);
            }

            $data['uid']=$uid;
            $data['name']=$name;
            $data['price']=$price;
            $data['num']=$num;
            $data['desc']=$desc;
            $data['imgs']=$imgs;
            $data['desc_imgs']=$imgs_desc;
            $data['create_time']=time();
            $res=M('goods')->add($data);
            if($res){
                return api_return(1,'发布成功');
            }else{
                return api_return(2,'发布失败');
            }
        }
	}

	//编辑商品
	public function edit_goods(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                $input = I('post.');
            }

            $key = $input['key'];
            $id = $input['id'];
            $name = $input['name'];
            $price = $input['price'];
            $num = $input['num'];
            $desc = $input['desc'];
            $goods_img = $input['goods_img'];
            $goods_img_desc = $input['desc_imgs'];
            $sys = $input['sys'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'id不能为空');
            if(empty($name)) return api_return(2,'请输入商品名称');
            if(empty($price)) return api_return(2,'请输入商品价格');
            if(empty($num)) return api_return(2,'请输入商品库存');
            if(empty($desc)) return api_return(2,'请输入商品描述');

            if($sys == 'IOS'){
                //IOS
                /**************商品图片上传**************/
                $base_imgs = $input['base_imgs'];
                if($base_imgs){
                    $base_imgs = base64_all_img($base_imgs);
                    $imgs = substr($base_imgs,0,-1);
                }

                if($goods_img){
                    if($imgs){
                        $data['imgs']=$goods_img.','.$imgs;
                    }else{
                        return api_return(2,'商品图片上传失败1');
                    }
                }else{
                    if($imgs){
                        $data['imgs'] = $imgs;
                    }else{
                        return api_return(2,'商品图片上传失败2');
                    }
                }
                /**************商品图片上传**************/

                /**************商品描述图片上传**************/
                $base_desc_imgs = $input['base_desc_imgs'];
                if($base_desc_imgs){
                    $base_desc_imgs = base64_all_img($base_desc_imgs);
                    $desc_imgs = substr($base_desc_imgs,0,-1);
                }

                if($goods_img_desc){
                    if($desc_imgs){
                        $data['desc_imgs'] = $goods_img.','.$desc_imgs;
                    }else{
                        return api_return(2,'商品描述图片上传失败3');
                    }
                }else{
                    if($desc_imgs){
                        $data['desc_imgs'] = $desc_imgs;
                    }else{
                        return api_return(2,'商品描述图片上传失败4');
                    }
                }
                /**************商品描述图片上传**************/
            }else{
                //安卓
                /**************商品图片上传**************/
                $file = $_FILES['imgs'];
                if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                    mkdir("Uploads/Picture/" . date("Y-m-d"));
                }

                // $img_id = "";
                $imgid = array();
                for ($i = 0; $i < count($file['tmp_name']); $i++) {
                    $str = stristr($file['name'][$i], '.');
                    if ($str != '') {
                        $path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "goods" . $str;
                    } else {
                        $path = '';
                    }

                    if ($path != '') {
                        if (copy($file['tmp_name'][$i], $path)) {
                            $imgurl['path'] = "/" . $path;
                            $imgurl['status'] = 1;
                            $imgurl['create_time'] = time();
                            $picture_id = D('picture')->add($imgurl);
                            if ($picture_id) {
                                $imgid[] = $picture_id;
                            }
                        } else {
                            return api_return(2,'提交失败');
                        }
                    }
                }
                $imgs = implode(',', $imgid);

                if($goods_img){
                    if($imgs){
                        //原来有商品图片，又上传了新商品图片
                        $data['imgs']=$goods_img.','.$imgs;
                    }else{
                        //原来又商品图片，这次没有上传新商品图片
                        $data['imgs']=$goods_img;
                    }
                }else{
                    if(count($file['tmp_name'])>0){
                        if(empty($imgs)){
                            return api_return(2,'商品图片上传失败4');
                        }else{
                            $data['imgs'] = $imgs;
                        }
                    }
                }
                /**************商品图片上传**************/

                /**************商品描述图片上传**************/
                $file_desc = $_FILES['desc_imgs'];
                if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                    mkdir("Uploads/Picture/" . date("Y-m-d"));
                }

                $imgid_desc = array();
                for ($i = 0; $i < count($file_desc['tmp_name']); $i++) {
                    $str = stristr($file_desc['name'][$i], '.');
                    if ($str != '') {
                        $path_desc = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "desc" . $str;
                    } else {
                        $path_desc = '';
                    }

                    if ($path_desc != '') {
                        if (copy($file_desc['tmp_name'][$i], $path_desc)) {
                            $imgurl_desc['path'] = "/" . $path_desc;
                            $imgurl_desc['status'] = 1;
                            $imgurl_desc['create_time'] = time();
                            $picture_id_desc = D('picture')->add($imgurl_desc);
                            if ($picture_id_desc) {
                                $imgid_desc[] = $picture_id_desc;
                            }
                        } else {
                            return api_return(2,'提交失败');
                        }
                    }
                }
                $imgs_desc = implode(',', $imgid_desc);

                if($goods_img_desc){
                    if($imgs_desc){
                        //原来有商品描述图片，现在有上传了新的商品描述图片
                        $data['desc_imgs']=$goods_img_desc.','.$imgs_desc;
                    }else{
                        $data['desc_imgs']=$goods_img_desc;
                    }
                }else{
                    if(count($file_desc['tmp_name'])>0){
                        //上传了新图片
                        if(empty($imgs_desc)){
                            return api_return(2,'商品描述图片上传失败2');
                        }else{
                            $data['desc_imgs']=$imgs_desc;
                        }
                    }
                }
                /**************商品描述图片上传**************/
            }

            $data['name'] = $name;
            $data['price'] = $price;
            $data['num'] = $num;
            $data['desc'] = $desc;
            $where['id'] = $id;

            $res = M("goods")->where($where)->save($data);
            if($res){
                return api_return(1,'编辑成功');
            }else{
                return api_return(2,'编辑失败');
            }
        }
	}

	//商品详情
	public function goods_detail(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'id不能为空');

            $where['id']=$id;
            $res = M('goods')->field('id,name,price,num,imgs,desc,desc_imgs')->where($where)->find();

            if($res){
                $res['comment_num']=M('comment')->where(['gid' => $id])->count();

                if(empty($res['imgs'])){
                    $res['imgurl'] = [];
                }else{
                    $img_map['id'] = array('IN',$res['imgs']);
                    $imgurl_list = M('picture')->field('id,path')->where($img_map)->select();
                    foreach($imgurl_list as $k => $v){
                        $res['imgurl'][$k]['id'] = $v['id'];
                        $res['imgurl'][$k]['path'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$v['path'];
                    }
                }

                if(empty($res['desc_imgs'])){
                    $res['imgurl_desc'] = [];
                }else{
                    $imgs_desc_map['id'] = array('IN',$res['desc_imgs']);
                    $imgurl_desc_list = M('picture')->field('id,path')->where($imgs_desc_map)->select();
                    if($imgurl_desc_list){
                        foreach($imgurl_desc_list as $k => $v){
                            $res['imgurl_desc'][$k]['id'] = $v['id'];
                            $res['imgurl_desc'][$k]['path'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$v['path'];
                        }
                    }else{
                        $res['imgurl_desc'] = [];
                    }
                }

                unset($res['imgs']);
                unset($res['desc_imgs']);
                return api_return(1,'success',$res);
            }else{
                return api_return(2,'无数据');
            }
        }
	}

	//下架，删除
	public function change_status(){
	    if(IS_POST){
	        $json_data = php_input();

	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];
            $type = $input['type'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'id不能为空');
            if(empty($type)) return api_return(2,'type不能为空');

            $where['id']=$id;

            if($type == 1){
                //下架
                $arr['status'] = 1;
            }elseif($type == 2){
                //删除
                $arr['status'] = 2;
            }else{
                $arr['status'] = 0;
            }

            $del = M('goods')->where($where)->save($arr);
            if($del){
                return api_return(1,'操作成功');
            }else{
                return api_return(2,'操作失败');
            }
        }
	}

	//店铺主页
	public function shop_page(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $name = $input['name'];
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'uid不能为空');

            $str=($n-1)*$num;
            $where['id'] = $uid;

            $res=array();
            $user=M('user')->field('id,nickname,age,sex,level,avatar_img')->where($where)->find();
            $user['avatar_img']=get_avatar($user['id']);

            $user['sale_num']=M('user')->where(['id' => $uid])->getField('sale_num');
            $res['shopinfo']=$user;

            $where1['uid'] = $uid;
            $where1['status'] = 0;
            if($name){
                $where1['name']=array('like','%'.$name.'%');
            }

            $goods=M('goods')->field('id,name,price,num,imgs')->where($where1)->limit($str,$num)->select();
            if($goods){
                foreach($goods as $k=>$v){
                    if($v['imgs']){
                        $img=explode(',',$v['imgs']);
                        $img=getImgurl($img[0]);
                        $goods[$k]['image']=$img;
                    }else{
                        $goods[$k]['image']='';
                    }
                    unset($goods[$k]['imgs']);
                }
                $res['goods']=$goods;
            }else{
                $res['goods']=array();
            }

            if($res){
                return api_return(1,'success',$res);
            }else{
                return api_return(2,'无数据');
            }
        }
	}

	/**
	 * 支付确认
	 * */
	public function pay_confirm(){
	    if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];//用户id
            $a_id = $input['a_id'];//商品id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'用户id不能为空');
            if(empty($a_id)) return api_return(2,'商品id不能为空');

            //收货地址信息
            $address_info = M('address')->field('id,username,mobile,city,area,detail')->where(['uid' => $uid,'is_default' => 1])->find();
            $address_id = $address_info['id']?$address_info['id']:'';//地址id
            $address_name = $address_info['username']?$address_info['username']:'';//姓名
            $address_mobile = $address_info['mobile']?$address_info['mobile']:'';//联系方式
            $address_detail = getarea($address_info['city']).getarea($address_info['area']).$address_info['detail']?getarea($address_info['city']).getarea($address_info['area']).$address_info['detail']:'';//联系地址

            $zs_blance = M('user')->where(['id' => $uid])->getField('zs_blance');//剩余钻石

            //商品清单
            $goods = M('goods')->where(['id' => $a_id])->find();
            $arr = explode(',',$goods['imgs']);
            $nickname = M('user')->where(['id' => $goods['uid']])->getField('nickname');
            $data = [
                'address_id' => $address_id,
                'address_name' => $address_name,
                'address_mobile' => $address_mobile,
                'address_detail' => $address_detail,
                'zs_blance' => $zs_blance?$zs_blance:0,
                'goods_id' => $a_id?$a_id:0,
                'goods_name' => $goods['name']?$goods['name']:'',
                'goods_img' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].get_img($arr[0]),
                'store_name' => $nickname.'的小店',
                'pay_price' => $goods['price']?$goods['price']:0
            ];

            return api_return(1,'获取数据成功',$data);
	    }
    }

	/**
	 * 提交订单
     * 生成待支付订单：余额不足
     * 生成已支付订单：余额充足
	 * */
	public function create_goodsorder(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];
            $uid = $input['uid'];
            $address_id = $input['address_id'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'商品id不能为空');
            if(empty($uid)) return api_return(2,'用户id不能为空');
            if(empty($address_id)) return api_return(2,'请选择收货地址');

            $zb_blance = M('user')->where(['id' => $uid])->getField('zs_blance');//用户剩余钻石

            $addr=M('address')->where("id=$address_id")->find();
            $where['id']=$id;
            $goods=M('goods')->where($where)->find();
            $goods_price = $goods['price'];
            $img=explode(',',$goods['imgs']);
            $addrs=getarea($addr['province']).getarea($addr['city']).getarea($addr['area']).$addr['detail'];
            $data['fuid']=$uid;
            $data['suid']=$goods['uid'];
            $data['goods_img']=$goods['goods_img'];
            $data['goods_price']=$goods_price;
            $data['goods_name']=$goods['name'];
            $data['goods_id']=$goods['id'];
            $data['goods_img']=$img[0];
            $data['mobile']=$addr['mobile'];
            $data['num']=1;
            $data['address_info']=$addrs;
            $data['order_sn']=setOrderSn();
            $data['contact_name']=$addr['username'];
            $data['zs_num']=$goods['price'];
            $data['create_time']=time();

            if($zb_blance < $goods_price){
                $data['order_status'] = 1;//订单状态（待支付）
                $res = M('order')->add($data);
                if($res){
                    return api_return(2,'钻石余额不足，已为您生成待支付订单');
                }else{
                    return api_return(2,'钻石余额不足且生成待支付订单失败');
                }
            }else{
                $data['order_status'] = 2;//订单状态（已支付）
                $res=M('order')->add($data);
                if($res){
                    M('goods')->where(['id' => $id])->setDec('num');//店铺商品-1
                    M('user')->where(['id' => $goods['uid']])->setInc('sale_num');//销售量+1
                    return api_return(1,'提交订单成功');
                }else{
                    return api_return(2,'提交订单失败');
                }
            }
        }
	}

	/**
	 * 待付款订单支付接口
	 * */
	public function buy_old_order(){
	    if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $order_id = $input['order_id'];//订单id

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($order_id)) return api_return(2,'订单id不能为空');

            $order_info = M('order')->field('order_status,fuid,suid,goods_price,goods_id')->where(['id' => $order_id])->find();
            if($order_info['order_status'] != 1) return api_return(2,'订单状态错误');

            $user_info = M('user')->field('zs_blance')->where(['id' => $order_info['fuid']])->find();
            if($user_info['zs_blance'] < $order_info['goods_price']) return api_return(2,'您的账户余额不足');

            $res = M('user')->where(['id' => $order_info['fuid']])->setDec('zs_blance',$order_info['goods_price']);
            if($res){
                $result = M('order')->where(['id' => $order_id])->setField(['order_status' => 2]);
                if($result){
                    M('goods')->where(['id' => $order_info['goods_id']])->setDec('num');
                    M('user')->where(['id' => $order_info['suid']])->setInc('sale_num');//销售量+1
                    return api_return(1,'支付成功');
                }else{
                    M('user')->where(['id' => $order_info['fuid']])->setInc('zs_blance',$order_info['goods_price']);
                    return api_return(2,'支付失败');
                }
            }else{
                return api_return(2,'支付失败');
            }

        }
    }

	//我的订单列表
    public function goods_orderlist(){
        if(IS_POST){
            $json_data = php_input();
            if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $uid = $input['uid'];
            $order_status = $input['order_status'];
            $type = $input['type'];//1：我的订单，2：客户订单
            $n = $input['n']?$input['n']:1;
            $num = $input['num']?$input['num']:10;

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($uid)) return api_return(2,'uid不能为空');
            if(empty($type)) return api_return(2,'订单类型不能为空');

            $str = ($n-1)*$num;
            if($type == 1){
                //我的订单条件
                $where = " 1 = 1 and fuid = " . $uid;
            }else{
                //客户订单条件
                $where = " 1 = 1 and suid = " . $uid;
            }

            if($order_status){
                if($order_status == 8){  //售后
                    $where .=" and order_status >7";
                }elseif($order_status == 7){   //全部
                    $where .= " and order_status !=6 and order_status!= 7";
                }else{
                    $where .= " and order_status = ".$order_status;
                }
            }else{
                $where .= " and order_status !=6 and order_status!= 7";
            }

            $res = M('order')->field('id,goods_id,order_sn,order_status,num,goods_name,goods_img,goods_price')->where($where)->limit($str,$num)->select();
            if($res){
                foreach($res as $k=>$v){
                    $res[$k]['goods_img']=getImgurl($v['goods_img']);
                    $goodsid=$v['goods_id'];
                    $res[$k]['price']=M('goods')->where("id=$goodsid")->getField('price');  //单价
//                    unset($res[$k]['goods_id']);
                }
                return api_return(1,'success',$res);
            }else{
                return api_return(1,'无数据',array());
            }
        }
    }

	//订单详情
	public function order_detail(){
	    if(IS_POST){
	        $json_data = php_input();

	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id'] = $oid;
            $res=M('order')->field('id,suid,order_sn,goods_id,goods_name,goods_img,address_info,mobile,num,goods_price,contact_name,order_status,create_time')->where($where)->find();
            $res['nickname'] = M('user')->where(['id' => $res['suid']])->getField('nickname');//用户昵称即为店铺名称
            $res['create_time'] = date('Y-m-d',$res['create_time']);

            if($res){
                $res['goods_img']=getImgurl($res['goods_img']);
                $goodsid=$res['goods_id'];
                $res['price']=M('goods')->where("id=$goodsid")->getField('price');  //单价
                unset($res['goods_id']);
                return api_return(1,'success',$res);
            }else{
                return api_return(2,'获取数据失败');
            }
        }
	}

	//立即购买
	public function buynow(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id'] = $oid;
            $info=M('order')->where($where)->find();
            $user=M('user')->field('zs_blance')->where("id=".$info['fuid'])->find();
            if($user['zs_blance']<$info['zs_num']){
                return api_return(2,'钻石余额不足，请充值');
            }else{
                $data['order_status']=2;
                M('user')->where("id=".$info['fuid'])->setDec('zs_blance',$info['zs_num']);
            }

            $res=M('order')->where($where)->save($data);
            if($res){
                $arr['uid']=$info['fuid'];
                $arr['zs_num']=$info['zs_num'];
                $arr['desc']='购买商品';
                $arr['create_time']=time();
                M('record')->add($arr);

                $suid = M('order')->where($where)->getField('suid');//收款人id
                $profit_to_zs = C('PROFIT_TO_ZS');//贡献度兑换钻石比例

                $inc_profit = $info['zs_num']/$profit_to_zs;
                M('user')->where(['id' => $suid])->setInc('profit',$inc_profit);

                return api_return(1,'购买成功');
            }else{
                return api_return(2,'购买失败');
            }
        }
	}

	//取消订单
	public function cancel_goodsorder(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id'] = $oid;
            $data['order_status'] = 6;
            $res=M('order')->where($where)->save($data);
            if($res){
                return api_return(1,'取消成功');
            }else{
                return api_return(2,'取消失败');
            }
        }
	}

	//发货
	public function deliver_goods(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];
            $express_id = $input['express_id'];
            $express_no = $input['express_no'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');
            if(empty($express_id)) return api_return(2,'请选择快递类型');
            if(empty($express_no)) return api_return(2,'请输入快递单号');

            $where['id'] = $oid;
            $data['order_status'] = 3;
            $data['express_id'] = $express_id;
            $data['express_no'] = $express_no;
            $res=M('order')->where($where)->save($data);
            if($res){
                return api_return(1,'发货成功');
            }else{
                return api_return(2,'发货失败');
            }
        }
	}

	//确认收货
	public function collect_goods(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id'] = $oid;
            $data['order_status'] = 4;
            $res=M('order')->where($where)->save($data);
            if($res){
                $info=M('order')->where($where)->find();
                M('user')->where("id=".$info['suid'])->setInc('zs_blance',$info['zs_num']);
                return api_return(1,'确认收货成功');
            }else{
                return api_return(2,'确认收货失败');
            }
        }
	}

	//删除订单
	public function del_order(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id']=$oid;
            $data['order_status']=7;
            $res=M('order')->where($where)->save($data);
            if($res){
                return api_return(1,'删除成功');
            }else{
                return api_return(2,'删除失败');
            }
        }
	}

	//退货退款
	public function apply_drawback(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                $input = I('post.');
            }

            $key = $input['key'];
            $oid = $input['oid'];
            $type_id = $input['type_id'];
            $explain = $input['explain'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');
            if(empty($type_id)) return api_return(2,'请选择类型');
            if(empty($explain)) return api_return(2,'退款退货说明不能为空');

            $where['id']=$oid;
            $orders=M('order')->where($where)->find();
            $data['zs_num']=$orders['zs_num'];
            $data['sorder_no']=$orders['order_sn'];
            $data['uid']=$orders['fuid'];
            $data['create_time']=time();
            $data['type_id']=$type_id;
            $data['oid']=$orders['id'];
            $data['explain']=$explain;
            $data['is_refund']=1;

            $base_imgs = $input['base_imgs'];

            if($base_imgs){
                //IOS图片上传
                $img_ids = base64_all_img($base_imgs);
                $imgs = substr($img_ids,0,-1);
            }else{
                //安卓图片上传
                $file = $_FILES['imgs'];
                if (!is_dir("Uploads/Picture/" . date("Y-m-d"))) {
                    mkdir("Uploads/Picture/" . date("Y-m-d"));
                }

                $imgid = array();
                for ($i = 0; $i < count($file['tmp_name']); $i++) {
                    $str = stristr($file['name'][$i], '.');
                    if ($str != '') {
                        $path = "Uploads/Picture/" . date("Y-m-d") . "/" . time() . $i . "back" . $oid . $str;
                    } else {
                        $path = '';
                    }

                    if ($path != '') {
                        if (copy($file['tmp_name'][$i], $path)) {
                            $imgurl['path'] = "/" . $path;
                            $imgurl['status'] = 1;
                            $imgurl['create_time'] = time();
                            $picture_id = D('picture')->add($imgurl);
                            if ($picture_id) {
                                //$picture[$i]['id'] = intval($picture_id);
                                $imgid[] = $picture_id;
                            }
                        } else {
                            return api_return(2,'提交失败');
                        }
                    }
                }
                $imgs = implode(',', $imgid);
            }

            $data['imgs']=$imgs;
            $res=M('drawback')->add($data);
            if($res){
                $arr['order_status']=8;
                M('order')->where("id=$oid")->save($arr);
                return api_return(1,'提交成功');
            }else{
                return api_return(2,'提交失败');
            }
        }
	}

	//查看售后
	public function drawback_detail(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'id不能为空');

            $where['oid']=$id;
            $res=M('drawback')->field('id,uid,type_id,create_time,imgs,explain,is_refund')->where($where)->find();
            if($res){
                $type_id=$res['type_id'];
                $res['type']=M('refusecate')->where("id=$type_id")->getField('name');
                $uwhere['id']=$res['uid'];
                $userinfo=M('user')->field('nickname,avatar_img')->where($uwhere)->find();
                $res['username']=$userinfo['nickname'];
                $res['avatar_img']=get_avatar($userinfo['avatar_img']);
                $imgs=explode(',', $res['imgs']);
                $array=array();
                foreach($imgs as $k=>$v){
                    $res['imgurl'][]=getImgurl($v);
                    $array[$k]['img']=$res['imgurl'][$k];
                }
                $res['imgurl']=$array;

                unset($res['imgs']);
                unset($res['uid']);
                unset($res['type_id']);
                return api_return(1,'success',$res);
            }else{
                return api_return(2,'获取数据失败');
            }
        }

	}

	//同意退货退款
	public function agree_drawback(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'id不能为空');

            $where['id']=$id;
            $data['status']=1;
            $res=M('drawback')->where($where)->save($data);
            if($res){
                $info = M('drawback')->field('oid,uid,zs_num')->where($where)->find();
                M('user')->where(['id' => $info['uid']])->setInc('zs_blance',$info['zs_num']);

                M('order')->where(['id' => $info['oid']])->setField(['order_status' => 9]);//修改订单状态

                return api_return(1,'提交成功');
            }else{
                return api_return(2,'提交失败');
            }
        }
	}

	//申诉
	public function appeal(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $id = $input['id'];
            $sx_reason = $input['sx_reason'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($id)) return api_return(2,'退货退款id不能为空');
            if(empty($sx_reason)) return api_return(2,'申诉理由不能为空');

            $where['id']=$id;
            $data['sx_reason']=$sx_reason;
            $data['sx_status']=1;
            $data['sx_time']=time();
            $res=M('drawback')->where($where)->save($data);
            if($res){
                return api_return(1,'提交成功');
            }else{
                return api_return(2,'提交失败');
            }
        }
	}

	//查看物流
	public function logistics(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];
            $oid = $input['oid'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');
            if(empty($oid)) return api_return(2,'订单id不能为空');

            $where['id']=$oid;
            $order=M('order')->field('express_id,order_sn,express_no')->where($where)->find();
            $express_id=$order['express_id'];
            $res=M('express')->where("id=$express_id")->find();

            //查询物流
            $num = $order['express_no'];
            $com =$res['code'];

            $post_data = array();
            $post_data["customer"] = '94B5EB89CAF0B36265FF974EA61985F3';
            $key= 'CdrfmsSw5290' ;
            $param = array('com'=>$com,'num'=>$num);
            $post_data["param"] = json_encode($param);
            $url='https://poll.kuaidi100.com/poll/query.do';

            $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
            $post_data["sign"] = strtoupper($post_data["sign"]);
            $o="";
            foreach ($post_data as $k=>$v)
            {
                $o.= "$k=".urlencode($v)."&";
            }
            $post_data=substr($o,0,-1);
            $data=curl($url,$post_data);
            $res = json_decode($data,true);


            if($res['returnCode']!=500){
                return api_return(1,'success',$res['data']);
            }else{
                return api_return(2,'获取数据失败');
            }
        }
	}

	//快递类型列表
	public function express_list(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $where['status']=array('neq',2);

            $res=M('express')->field('id,name')->where($where)->select();
            if($res){
                return api_return(1,'success',$res);
            }else{
                return api_return(1,'无数据',array());
            }
        }
	}

	//退货退款类型
	public function refuse_type_list(){
	    if(IS_POST){
	        $json_data = php_input();
	        if(!is_null(json_decode($json_data))){
                //json数据，IOS请求数据
                $input = json_decode($json_data,true);
            }else{
                //非json数据，安卓请求数据
                parse_str($json_data, $input);
            }

            $key = $input['key'];

            if($key != C('ONLY_KEY')) return api_return(2,'唯一标识错误');

            $where['status']=array('neq',2);
            $res=M('refusecate')->field('id,name')->where($where)->select();
            if($res){
                return api_return(1,'success',$res);
            }else{
                return api_return(1,'无数据',array());
            }
        }
	}
}
